<?php


namespace app\common\business;


use app\common\lib\Key;
use think\Exception;
use think\facade\Cache;

class Cart extends BusBase
{
    public function insertRedis($user_id, $sku_id, $num)
    {
        $goods_sku = (new GoodsSku())->getGoodsDetailBySkuId($sku_id);
        if (!$goods_sku) {
            return FALSE;
        }

        //价钱不用保存,因为价格是会变的
        $data = [
            'title' => $goods_sku['goods']['title'],
            'image' => $goods_sku['goods']['recommend_image'],
            'num' => $num,
            'goods_id' => $goods_sku['goods']['id'],
            'create_time' => time(),
        ];

        try {
            //先查有没有这个商品
            $get = Cache::store('redis')->hget(Key::userCart($user_id), $sku_id);
            $get = json_decode($get, true);
            if ($get) {
                $data['num'] += $get['num'];
            }

            $res = Cache::store('redis')->hset(Key::userCart($user_id), $sku_id, json_encode($data));
        } catch (Exception $e) {
            return FALSE;
        }

        return $res;
    }

    public function lists($user_id, $ids)
    {
        try {
            if ($ids) {
                $ids = explode(',', $ids);
                $res = Cache::store('redis')->hMget(Key::userCart($user_id), $ids);
                //防止用户传递不合法的id
                if (in_array(false, $res)) {
                    return [];
                }
            } else {
                $res = Cache::store('redis')->hGetAll(Key::userCart($user_id));
            }
        } catch (Exception $e) {
            return [];
        }

        if (!$res) {
            return [];
        }

        $sku_ids = array_keys($res);
        $skus = (new \app\common\model\mysql\GoodsSku())->getNormalIndIds($sku_ids);
        $sku_id_price = array_column($skus, 'price', 'id');
        $sku_specs_value_ids = array_column($skus, 'specs_value_ids', 'id');
        $skus = (new SpecsValue())->dealSpecsValue($sku_specs_value_ids);

        //sku_id 对应 库存
        $stocks = array_column($res, 'stock', 'id');

        $data = [];
        foreach ($res as $key => $v) {
            $v = json_decode($v, true);
            if ($ids && isset($stocks[$key]) && $stocks[$key] < $v['num']) {
                throw  new Exception($v['title'] . '的商品库存不足');
            }

            $price = $sku_id_price[$key] ?? 0;
            $v['price'] = $price;
            $v['total_price'] = $price * $v['num'];     //当前sku的总价
            $v['id'] = $key;
            $v['sku'] = $skus[$key];
            $data[$key] = $v;
        }

        //购物车列表排序
        if (!empty($data)) {
            $array_column = array_column($data, 'create_time');
            array_multisort($array_column, SORT_DESC, $data);
        }


        return $data;
    }

    public function del($user_id, $ids)
    {
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }

        try {
            $res = Cache::store('redis')->hDel(Key::userCart($user_id), ...$ids);
        } catch (Exception $e) {
            return FALSE;
        }
        return $res;
    }

    public function update($user_id, $id, $num)
    {
        try {
            $sku = Cache::store('redis')->hGet(Key::userCart($user_id), $id);
            $sku = json_decode($sku, true);
            $sku['num'] = $num;
            $res = Cache::store('redis')->hSet(Key::userCart($user_id), $id, json_encode($sku));
        } catch (Exception $e) {
            return false;
        }
        return $res;
    }

    public function getCount(string $user_id)
    {
        try {
            $count = Cache::store('redis')->hLen(Key::userCart($user_id));
        } catch (Exception $e) {
            return 0;
        }
        return $count;
    }


}